package com.zsrt.java.day20161227.wrl.demo03;

import java.util.Arrays;

import org.junit.Test;

public class ArrayTest {
	
	/**
	 * 优化：
	 * 给出一个数组，然后修改一个元素，返回一个数组
	 * @param oldArrays	数组
	 * @param num	需要修改的项
	 * @param number1	修改后的值
	 * @return	删除参数后的数组
	 */
	public static int[] add04(int[] oldArrays,int num,int number2){
		int length = oldArrays.length;
		int[] newArrays = new int[length];
		
		//获取下标
		for(int i = 0;i<length;i++){
			if(num == oldArrays[i]){
				newArrays[i] = number2;
			}else{
				newArrays[i] = oldArrays[i];
			}
		}
		return newArrays;
	}
	
	/**
	 * 优化：
	 * 给出一个数组，然后删除一个元素，返回一个数组
	 * @param oldArrays	数组
	 * @param num	需要删除的参数
	 * @return	删除参数后的数组
	 */
	public static int[] add03(int[] oldArrays,int num){
		int length = oldArrays.length-1;
		int[] newArrays = new int[length];
		int index = 0;
		
		//获取下标
		for(int i = 0;i<length;i++){
			if(num == oldArrays[i]){
				index = i;
			}
		}
		for(int i = 0;i < index;i++){
			newArrays[i] = oldArrays[i];
		}
		for(int i = index; i < length; i++){
			newArrays[i] = oldArrays[i+1];
		}
		return newArrays;
	}

	/**
	 * 给出一个数组，然后删除一个元素，返回一个数组
	 * 
	 */
	@Test
	public void add02(){
		int[] oldArrays = new int[]{5,8,4,9,2,1};
		
		//1 找到3的下标
		int index3 = 3;
		
		//创建一个新的数组old.length-1
		int length = oldArrays.length - 1;
		int[] newAs = new int[length];
		
		//遍历老数组
		//3.1 如果下标比index3小，原样复制
		for(int first = 0;first < index3;first++){
			newAs[first] = oldArrays[first];
		}
		
		//3.2 下标大于index3，
		for(int sec = index3;sec < length;sec++){
			newAs[sec] = oldArrays[sec+1];
		}
		for(int value : newAs){
			System.out.print(value + " ");
		}
	}
	
	@Test
	public void add01(){
		int[] oldArrays = {5,8,4,9,2,1,55};
		System.out.println("修改前："+Arrays.toString(oldArrays));
		
		int n1 = 9;
		int n2 = 99;
		
//		int[] newAs = add03(oldArrays, 2);
//		System.out.println("修改后："+Arrays.toString(newAs));
		/*for(int value : newAs){
			System.out.print(value + " ");
		}*/
		
		
		int[] newAs = add04(oldArrays, n1,n2);
		System.out.println("---用"+n2+"替换"+n1+"---");
		System.out.println("修改后："+Arrays.toString(newAs));
	}

}
